import os
import threading
import time

import requests
from git.repo import Repo

from logger import log


# 读取本地版本文件并返回版本号
def read_local_version_file():
    try:
        with open('./version.m3u', 'r') as f:
            return f.read().strip()
    except FileNotFoundError as e1:
        return None


# 比较是否需要升级
def compare_local_version(local_version):
    if local_version is None:
        return True
    remote_version = get_remote_version()
    if remote_version is None:
        return False
    return local_version != remote_version


# 获取仓库版本号
def get_remote_version():
    try:
        url = "http://gitee.com/lipeng260/webcam/raw/main/version.m3u"
        # 设置请求头以禁用缓存
        headers = {
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache'
        }
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 如果请求失败则抛出异常
        # 提取远程版本号
        remote_version = response.text.strip()
        return remote_version
    except requests.RequestException as e:
        return None
    except Exception as e:
        return None


# 执行git pull 命令
def download_file():
    local_path = os.path.join('./')
    repo = Repo(local_path)
    repo.git.pull()


# win下中断程序执行
def kill_server(pid):
    # 判断系统类型 win os
    # 本函数用于中止传入pid所对应的进程
    if os.name == 'nt':
        # Windows系统
        cmd = 'taskkill /pid ' + str(pid) + ' /f'
        try:
            os.system(cmd)
            log.info(f'nt {pid} killed')
        except Exception as e:
            log.error(f'nt {pid} kill error', e)
    elif os.name == 'posix':
        # Linux系统
        cmd = 'kill ' + str(pid)
        try:
            os.system(cmd)
            log.info(f'posix {pid} killed')
        except Exception as e:
            log.error(f'posix {pid} kill error', e)
    else:
        log.warn('Undefined os.name')


# 更新服务器版本
def update_server_version(host, id):
    try:
        local_version = read_local_version_file()
        if local_version is not None:
            url = f'https://{host}/api/weigh/internal/vsEdge/updateVersion'
        data = {
            "id": id,
            "version": local_version
        }
        response = requests.post(url, json=data)
        response.raise_for_status()  # 如果请求失败则抛出异常
        return True
    except requests.RequestException as e:
        return False


# 更新版本入口
def version_check(pid, host, id):
    def check():
        while True:
            print("start")
            version = read_local_version_file()
            need_download = compare_local_version(version)
            if need_download:
                download_file()
                success = update_server_version(host, id)
                if success:
                    kill_server(pid)
            print("end")
            time.sleep(60)

    thread = threading.Thread(target=check)
    thread.start()
